package com.main.action;

import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.main.util.PropertiesRead;
import com.main.util.PropertiesUtil;

@Controller   //类似Struts的Action  
@RequestMapping("/properties") 
public class Properties {
	
	@RequestMapping(value="/manager",method=RequestMethod.GET)
    public ModelAndView index(){
		PropertiesRead pr=new PropertiesRead();
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/properties/propertisManager");
        mv.addObject("fileNames", pr.getFileNameList());
        return mv;
    }
	
	@ResponseBody
	@RequestMapping(value="/getContent",method=RequestMethod.POST)
    public Map<String,String> getContent(@RequestBody JSONObject json){
		PropertiesRead pr=new PropertiesRead();
		String content=pr.getFileContent(json.getString("name"));
		Map<String,String>result=new HashMap<String,String>();
		result.put("result", "success");
		result.put("content", content);
		return result;
    }
	
	
	@ResponseBody
	@RequestMapping(value="/saveContent",method=RequestMethod.POST)
    public Map<String,String> saveContent(@RequestBody JSONObject json){
		PropertiesRead pr=new PropertiesRead();
		String name=json.getString("name");
		String content=json.getString("content");
		String names[]=pr.getFileNameList();
		Map<String,String>result=new HashMap<String,String>();
		if(null==name||"".equals(name)){
		 result.put("result", "error");
		 result.put("message", "文件名无效");
		 return result;
		}
		boolean isHas=false;
		for(String str:names){
			if(str.contains(name)){
				isHas=true;
				break;
			}
		}
		if(!isHas){
		result.put("result", "error");
		result.put("message", "没有此文件名");
		return result;
		}
		
        pr.saveFileContent(name, content);
        PropertiesUtil.getProtertiesUtil().destory();
        PropertiesUtil.getProtertiesUtil().init();
        
        result.put("result", "success");
		return result;
    }
}
